package com.github.zzay.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.zzay.admin.dto.AdminDto;
import com.github.zzay.admin.entity.Admin;
import com.github.zzay.admin.mapper.AdminMapper;
import com.github.zzay.admin.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zzay
 * @className AdminServiceImpl
 * @description Implementation class of "AdminService".
 * @create 2022/07/05 15:55
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    /**
     * Admin mapper instance.
     */
    @Autowired
    private AdminMapper adminMapper;

    /**
     * Register an admin account.
     *
     * @param adminDto Admin DTO
     * @return Operation result
     */
    @Override
    public Boolean register(AdminDto adminDto) {
        // get username and password
        String username = adminDto.getUsername();
        String password = adminDto.getPassword();
        String email = adminDto.getEmail();
        // check whether the username has been user or not
        Admin admin = adminMapper.selectByUsername(username);
        if (admin != null) {
            return false;
        }
        // create a new admin record and insert it
        Admin newAdmin = new Admin(username, new BCryptPasswordEncoder().encode(password));
        newAdmin.setEmail(email);
        log.info("======== Register: " + username + "-" + password + " ========");
        return this.save(newAdmin);
    }

    /**
     * Log in of an admin account.
     *
     * @param adminDto Admin DTO
     * @return Operation result
     */
    @Override
    public Boolean login(AdminDto adminDto) {
        String username = adminDto.getUsername();
        String password = adminDto.getPassword();
        Admin admin;
        if (username.contains("@")) {
            admin = adminMapper.selectByEmail(username);
        } else {
            admin = adminMapper.selectByUsername(username);
        }
        if (admin == null) {
            return false;
        }
        log.info("======== Login: " + username + "-" + password + " ========");
        return new BCryptPasswordEncoder().matches(password, admin.getPassword());
    }

    /**
     * Log out of an admin account.
     *
     * @param adminDto Admin DTO
     * @return Operation result
     */
    @Override
    public Boolean logout(AdminDto adminDto) {
        return true;
    }

}
